import csv
import json
import os
import traceback
from operator import itemgetter


class File_Process():
    def __init__(self):
        pass

    @staticmethod
    def get_record_path(path):
        try:
            if path:
                path_list = path.split('/')[:-1]
                load_path = path_list[0]
                for i in range(len(path_list) - 1):
                    load_path += '/' + path_list[i + 1]
            else:
                load_path = '.'
        except Exception as e:
            load_path = '.'
        return load_path

    # @staticmethod
    # def get_table_info(file_path, logger):
    #     if not os.path.exists(file_path):
    #         return False, '没有该路径'
    #     index = {}
    #     data = []
    #     try:
    #         with open(file_path, 'r', encoding='utf-8') as f:
    #             tmp = csv.reader(f)
    #             i = 0
    #             for line in tmp:
    #                 if i == 0:
    #                     for idx, value in enumerate(line):
    #                         index[value] = idx
    #                 elif line[0] != '':
    #                     data.append(line)
    #                 i += 1
    #     except UnicodeDecodeError:
    #         try:
    #             with open(file_path, 'r', encoding='GBK') as f:
    #                 tmp = csv.reader(f)
    #                 i = 0
    #                 for line in tmp:
    #                     if i == 0:
    #                         for idx, value in enumerate(line):
    #                             index[value] = idx
    #                     elif line[0] != '':
    #                         data.append(line)
    #                     i += 1
    #         except UnicodeDecodeError:
    #             return False, '编码格式有问题'
    #
    #     index['row'] = len(index)
    #     # 处理data数据
    #     for i in range(len(data)):
    #         # 如果没有二级类型就用一级类型代替
    #         if not data[i][index['2级类型']]:
    #             data[i][index['2级类型']] = data[i][index['1级类型']]
    #         # 如果没有参数名就用参数名英代替
    #         if not data[i][index['参数名']]:
    #             data[i][index['参数名']] = data[i][index['参数名英']]
    #         # 'A' + '-' + '系统'
    #         data[i][index['1级类型']] = data[i][index['类型号']][0] + '_' + data[i][index['1级类型']]
    #         # 'A0' + '-' + '状态监视'
    #         data[i][index['2级类型']] = data[i][index['类型号']] + '_' + data[i][index['2级类型']]
    #         # 将'选择型操作定义'  str --> dict
    #         if data[i][index['数据类型']] in ['5', '3', 'bit', 'enum']:
    #             dict_temp = {}
    #             operate_str = data[i][index['选择型操作定义']]
    #             # 如果有选择型操作定义
    #             if operate_str not in ['0', '']:
    #                 # 如果是旧的类型定义
    #                 if '-' in operate_str:
    #                     b = operate_str.split(';')
    #                     for j in range(len(b)):
    #                         if b[j]:
    #                             if '；' in b[j]:
    #                                 d = b[j].split('；')
    #                                 for k in range(len(d)):
    #                                     dict_temp[d[k].split('-', 1)[0]] = d[k].split('-', 1)[1]
    #                             else:
    #                                 dict_temp[b[j].split('-', 1)[0]] = b[j].split('-', 1)[1]
    #                 # 如果是新的类型定义
    #                 else:
    #                     # 如果有:说明是字典类型
    #                     if ':' in operate_str or '：' in operate_str:
    #                         list_def_name = []
    #                         c = operate_str.split(',')
    #                         for j in range(len(c)):
    #                             if '，' in c[j]:
    #                                 d = c[j].split('，')
    #                                 for k in range(len(d)):
    #                                     if d[k]:
    #                                         list_def_name.append(d[k])
    #                             elif c[j]:
    #                                 list_def_name.append(c[j])
    #                         for j in range(len(list_def_name)):
    #                             if ':' in list_def_name[j]:
    #                                 d = list_def_name[j].split(':')
    #                                 if d[0]:
    #                                     dict_temp[d[0]] = d[1]
    #                                 else:
    #                                     dict_temp[str(j)] = d[1]
    #                             elif '：' in list_def_name[j]:
    #                                 d = list_def_name[j].split('：')
    #                                 if d[0]:
    #                                     dict_temp[d[0]] = d[1]
    #                                 else:
    #                                     dict_temp[str(j)] = d[1]
    #                             elif list_def_name[i]:
    #                                 dict_temp[str(j)] = list_def_name[j]
    #                     # 否则就按list类型去处理
    #                     else:
    #                         list_def_name = []
    #                         c = operate_str.split(',')
    #                         for j in range(len(c)):
    #                             if '，' in c[j]:
    #                                 d = c[j].split('，')
    #                                 for k in range(len(d)):
    #                                     if d[k]:
    #                                         list_def_name.append(d[k])
    #                             elif c[j]:
    #                                 list_def_name.append(c[j])
    #                         for key, value in enumerate(list_def_name):
    #                             dict_temp[str(key)] = value
    #
    #             data[i][index['选择型操作定义']] = dict_temp
    #         # 追加1列数据 'ID'
    #         data[i].append(i)
    #
    #     # 根据 '日志输出' 和 'EEPROM变量' 重新排序
    #     data2 = sorted(data, key=itemgetter(index['日志输出']), reverse=True)
    #     data2 = sorted(data2, key=itemgetter(index['EEPROM变量']), reverse=True)
    #     # # 添加排序后的索引,并追加3列'定位', '状态字', '当前值'
    #     # index['ADDR'] = len(index)
    #     # index['定位'] = len(index)
    #     # index['状态字'] = len(index)
    #     # index['当前值'] = len(index)
    #     # for i in range(len(data2)):
    #     #     data2[i].append(i)
    #     #     data2[i].append(None)
    #     #     data2[i].append(None)
    #     #     data2[i].append(0)
    #
    #     # 将二维list(data) --> dict{'name': [value]}
    #     table_info = {}
    #     index_list = list(index.keys())
    #     for i in range(len(index_list)):
    #         temp_list = []
    #         for j in range(len(data2)):
    #             temp_list.append(data2[j][i])
    #         table_info[index_list[i]] = temp_list
    #     # 追加序列
    #     temp_list1 = [None] * len(table_info['类型号'])
    #     temp_list2 = [None] * len(table_info['类型号'])
    #     temp_list3 = [None] * len(table_info['类型号'])
    #     temp_list4 = [0] * len(table_info['类型号'])
    #     temp_list5 = [None] * len(table_info['类型号'])
    #     for i in range(len(temp_list1)):
    #         temp_list1[i] = i
    #         temp_list5[i] = table_info['类型号'][i] + '-' + table_info['参数名英'][i]
    #     table_info['ADDR'] = temp_list1
    #     table_info['定位'] = temp_list2
    #     table_info['状态字'] = temp_list3
    #     table_info['当前值'] = temp_list4
    #     table_info['unique_ID'] = temp_list5
    #
    #     return True, table_info

    # @staticmethod
    # def save_default_to_csv(csv_path, table_info):
    #     index = {}
    #     data = []
    #     try:
    #         with open(csv_path, 'r', encoding='utf-8') as f:
    #             tmp = csv.reader(f)
    #             i = 0
    #             for line in tmp:
    #                 if i == 0:
    #                     header = line
    #                     for idx, value in enumerate(line):
    #                         index[value] = idx
    #                 else:
    #                     data.append(line)
    #                 i += 1
    #         code_type = 'utf-8'
    #     except:
    #         with open(csv_path, 'r', encoding='GBK') as f:
    #             tmp = csv.reader(f)
    #             i = 0
    #             for line in tmp:
    #                 if i == 0:
    #                     header = line
    #                     for idx, value in enumerate(line):
    #                         index[value] = idx
    #                 else:
    #                     data.append(line)
    #                 i += 1
    #         code_type = 'GBK'
    #     for i in range(len(table_info['当前值'])):
    #         old_num = table_info['当前值'][i]
    #         # old_num = self.paras_view[i][self.window.index['当前值']]
    #
    #         # print(self.table_paras.item(i, 1).text(), self.table_paras.item(i, 2).text(), old_num)
    #         for j in range(len(data)):
    #             if table_info['uniqueID'][i] == data[j][index['类型号']] + '-' + data[j][index['参数名英']]:
    #                 data[j][index['缺省值']] = old_num
    #                 break
    #     # 将缺省值改变
    #     for i in range(len(data)):
    #         if data[i][index['参数名']]:
    #             if data[i][index['数据类型']] in ['5', 'bit']:
    #                 data[i][index['数据类型']] = 'bit'
    #             elif data[i][index['数据类型']] in ['3', 'enum']:
    #                 data[i][index['数据类型']] = 'enum'
    #             elif data[i][index['数据类型']] in ['1', 'int']:
    #                 data[i][index['数据类型']] = 'int'
    #             else:
    #                 data[i][index['数据类型']] = 'float'
    #
    #     try:
    #         with open(csv_path, 'w', newline='', encoding=code_type) as f:
    #             f_csv = csv.writer(f)
    #             f_csv.writerow(header)
    #             f_csv.writerows(data)
    #         return True
    #     except Exception as e:
    #         return False
    #
    # @staticmethod
    # def get_header_data(table_info, pre_name, adr_name, def_name):
    #     headr_data = ''
    #     count = 0  # 记录EEPROM的个数
    #     for i in range(len(table_info['isEEPROM'])):
    #         if table_info['isEEPROM'][i] == 1:
    #             count += 1
    #
    #     headr_data += '#ifndef ' + def_name.upper() + '_H\n' + '#define ' + def_name.upper() + '_H\n\n'
    #     headr_data += '#define EEPROM_SAVE_NUM ' + str(count) + '       //需要存储的数量\n'
    #
    #     for i in range(len(table_info['isEEPROM'])):
    #         if table_info['var_name'][i]:
    #             if table_info['var_type'][i] in ['5', '3', '1', 'bit', 'enum', 'int']:
    #                 headr_data += '#define ' + pre_name + table_info['category_id'][i] + '_' + \
    #                               table_info['var_name'][i] + ' ' + adr_name + '.u32[' + str(
    #                     i) + ']      // ' + table_info['var_name'][i] + '\n'
    #             else:
    #                 headr_data += '#define ' + pre_name + table_info['category_id'][i] + '_' + \
    #                               table_info['var_name'][i] + ' ' + adr_name + '.f32[' + str(
    #                     i) + ']      // ' + table_info['var_name'][i] + '\n'
    #         else:
    #             if table_info['var_type'][i] in ['5', '3', '1', 'bit', 'enum', 'int']:
    #                 headr_data += '#define ' + pre_name + table_info['category_id'][i] + '_' + 'Var' + str(
    #                     i) + ' ' + adr_name + '.u32[' + str(i) + ']      // ' + table_info['var_name'][
    #                                   i] + '\n'
    #             else:
    #                 headr_data += '#define ' + pre_name + table_info['category_id'][i] + '_' + 'Var' + str(
    #                     i) + ' ' + adr_name + '.f32[' + str(i) + ']      // ' + table_info['var_name'][
    #                                   i] + '\n'
    #
    #     headr_data += '\n#endif\n'
    #     return headr_data
